package com.cmsky.open.core.util;

import java.io.StringWriter;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.map.ObjectMapper;

public class JsonUtils {
	private static final Log log = LogFactory.getLog(JsonUtils.class);
	
	private static final ObjectMapper mapper = new ObjectMapper();
    public static String jsonFromObject(Object object) {
        StringWriter writer = new StringWriter();
        try {
            mapper.writeValue(writer, object);
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            log.error("Unable to serialize to json: " + object, e);
            return null;
        }
        return writer.toString();
    }

   public static <T> T objectFromJson(String json, Class<T> klass) {
        T object;
        try {
            object = mapper.readValue(json, klass);
        } catch (RuntimeException e) {
            log.error("Runtime exception during deserializing "
                    + klass.getSimpleName() + " from "
                    + StringUtils.abbreviate(json, 80));
            throw e;
        } catch (Exception e) {
            log.error("Exception during deserializing " + klass.getSimpleName()
                    + " from " + StringUtils.abbreviate(json, 80));
            return null;
        }
        return object;
    }
  
   
   public static Map mapFromJson(String json) {
       return (Map) objectFromJson(json, Map.class);
   }
   public static List listFromJson(String json) {
       return (List) objectFromJson(json, List.class);
   }
}
